import React, { useEffect, useState } from "react";
import { Navigate, useNavigate, useParams } from "react-router-dom";
import request from "../../utils/request";
import { ItemState } from "../product";
import { CartO, ChatO, ShopO } from "@react-vant/icons";
import { ActionBar, Button } from "react-vant";
import { useDispatch } from "react-redux";
import { addCar } from "../../store/car/carReduce";
const Index = () => {
  const { id } = useParams();
  const [detail, setDetail] = useState<ItemState>();
  const [size, setSize] = useState("165");
  const [color, setColor] = useState("红色");
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const fetchDetail = async () => {
    const resp = await request.get("/api/detail", { params: { id } });
    setDetail(resp.data.data);
  };
  const handleAddCar = () => {
    if (detail)
      dispatch(
        addCar({
          ...detail,
          count: 1,
          size,
          color,
          checked: false
        })
      );
  };
  useEffect(() => {
    fetchDetail();
  }, []);

  if (!detail) {
    return <div>...</div>;
  }

  return (
    <div>
      <div>
        <img width={"100%"} src={detail.url} alt="" />
        <h3>{detail.title}</h3>
        <p>{detail.desc}</p>
        <p>￥： {detail.price}</p>
      </div>

      <div className="sku">
        <div className="sku-item">
          <span>颜色：</span>
          <div>
            {detail.sku.colors.map((v, i) => {
              return (
                <Button
                  key={i}
                  onClick={() => setColor(v)}
                  type={v === color ? "primary" : "default"}
                >
                  {v}
                </Button>
              );
            })}
          </div>
        </div>

        <div className="sku-item">
          <span>大小：</span>
          <div>
            {detail.sku.size.map((v, i) => {
              return (
                <Button
                  key={i}
                  onClick={() => setSize(v)}
                  type={v === size ? "primary" : "default"}
                >
                  {v}
                </Button>
              );
            })}
          </div>
        </div>
      </div>

      <ActionBar>
        <ActionBar.Icon
          icon={<ChatO />}
          text="客服"
          onClick={() => console.log("chat click")}
        />
        <ActionBar.Icon
          icon={<CartO />}
          text="购物车"
          onClick={() => navigate("/car")}
        />
        <ActionBar.Icon
          icon={<ShopO />}
          text="店铺"
          onClick={() => console.log("shop click")}
        />
        <ActionBar.Button
          type="danger"
          text="立即购买"
          onClick={() => handleAddCar()}
        />
      </ActionBar>
    </div>
  );
};

export default Index;
